const fetch = require("node-fetch");
const path = require("path");
const fs = require("fs");
const download = require('download')
const {ROOT_DIR} = require('./config')

const getResContentType = async (url) => {
  const res = await fetch(url);
  return res.headers.get("content-type");
};

const isDownloadFileURL = async (url) => {
  const contentType = await getResContentType(url);
  return !(contentType.indexOf("text/html") > -1);
};

const downloadFile = async (url, fileName, singerName) => {
  console.log('fileName: ', fileName);
  const dir = path.resolve(ROOT_DIR, singerName);
  console.log('--- root dir -----: ', dir);
  fs.writeFileSync(`${dir}/${fileName}`, await download(url));
};

const getIframeContent = async (page) => {
  await page.waitForSelector('iframe'); // 替换为你的iframe选择器
  const ele = await page.$("iframe");
  // 切换到iframe
  const framePage = await page.frames().find(f => !!f.name()); // 替换为你的iframe名称
  if (framePage) {
    // 在iframe中执行操作，例如获取文本
    const content = await framePage.$eval('a', element => element.href); // 替换为你想获取内容的选择器和需要执行的操作
    console.log(content); // 输出iframe中的内容

  }
}
const getMusicExceptionIndex = (singerName, musicName, index, url) => {
  const str1 = `----${new Date()} ${singerName} 的歌曲 ${musicName} 获取失败，请重试 -----`
  const str2 = `---- ${musicName} 下载地址： ${url}`
  const filePath = `${__dirname}/log/${singerName}_${index}.log`;
  console.log(filePath)
  if (fs.existsSync(filePath)) {
    return index + 1
  }
  const str = [str1, str2].join('\n')
  index < 50 && fs.writeFileSync(filePath, str);
  return index
}
//test
// isDownloadFileURL('https://api.liumingye.cn/m/api/link?id=d3f636iePH3nJMVUD1wG_Hzaxfbcy6eU0RdCgWp7ec0YMiXmec_c&quality=320&_t=1723129947862&token=20240531.b0d2880e6257314a2a7d760d7c8cb0f1')
module.exports = {
  isDownloadFileURL,
  downloadFile,
  getIframeContent,
  getMusicExceptionIndex
};
